/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cl.alanis.gui;

import cl.alanis.business.VentaBusiness;
import cl.alanis.dto.NotaCreditoDto;
import cl.alanis.dto.StockDto;
import cl.alanis.dto.VentaDto;
import cl.alanis.util.AlanisLog;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;


/**
 *
 * @author Pía
 */
public class VentaAnulaGui extends javax.swing.JDialog {
    Logger logger=AlanisLog.obtenerLogger(VentaAnulaGui.class);
    SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
    List stocks=new ArrayList();
    Double sumaValor =new Double(0);
    /**
     * Creates new form VentaAnulaGui
     */
    public VentaAnulaGui() {
        this.setModal(true);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtNumBoleta = new javax.swing.JTextField();
        bttBuscarVentaAnula = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tblListaPPVentaAnula = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        bttCancelarVentaAnula = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        lblTituloAnulaVenta = new javax.swing.JLabel();
        lblError = new javax.swing.JLabel();
        lblCodigoVentaAnula = new javax.swing.JLabel();
        lblFechaVentaAnula = new javax.swing.JLabel();
        lblVentaTotalVentaAnula = new javax.swing.JLabel();
        bttLimpiarVentaAnula = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();
        txtDescripcion = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nùmero de boleta:");

        txtNumBoleta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNumBoletaActionPerformed(evt);
            }
        });

        bttBuscarVentaAnula.setText("Buscar Venta");
        bttBuscarVentaAnula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttBuscarVentaAnulaActionPerformed(evt);
            }
        });

        jLabel2.setText("INFORMACIÓN VENTA");

        jLabel3.setText("Código Venta");

        jLabel4.setText("Fecha");

        jLabel5.setText("Valor Total Venta");

        tblListaPPVentaAnula.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Descripción", "Valor"
            }
        ));
        tblListaPPVentaAnula.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblListaPPVentaAnula.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblListaPPVentaAnulaMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(tblListaPPVentaAnula);

        jLabel6.setText("INFORMACION PRODUCTO");

        bttCancelarVentaAnula.setText("Cancelar");
        bttCancelarVentaAnula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttCancelarVentaAnulaActionPerformed(evt);
            }
        });

        lblTituloAnulaVenta.setText("- ANULA VENTA -");

        lblError.setForeground(new java.awt.Color(255, 51, 51));
        lblError.setText("-");

        lblCodigoVentaAnula.setText("----");

        lblFechaVentaAnula.setText("----");

        lblVentaTotalVentaAnula.setText("----");

        bttLimpiarVentaAnula.setText("Limpiar");
        bttLimpiarVentaAnula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttLimpiarVentaAnulaActionPerformed(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.setEnabled(false);
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        jLabel7.setText("Descripción:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap(18, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(txtNumBoleta, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(15, 15, 15))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel5)
                                            .addComponent(jLabel4))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(lblVentaTotalVentaAnula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(lblCodigoVentaAnula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(lblFechaVentaAnula, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(0, 0, Short.MAX_VALUE)))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(bttBuscarVentaAnula)
                                .addGap(132, 132, 132)
                                .addComponent(lblError, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel6))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAceptar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bttLimpiarVentaAnula)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bttCancelarVentaAnula))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(286, 286, 286)
                        .addComponent(lblTituloAnulaVenta)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap(55, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(lblTituloAnulaVenta)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNumBoleta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bttBuscarVentaAnula)
                    .addComponent(lblError))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(lblCodigoVentaAnula))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(lblFechaVentaAnula))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(lblVentaTotalVentaAnula))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bttCancelarVentaAnula)
                    .addComponent(bttLimpiarVentaAnula)
                    .addComponent(btnAceptar))
                .addGap(68, 68, 68))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtNumBoletaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNumBoletaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNumBoletaActionPerformed

    private void bttBuscarVentaAnulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttBuscarVentaAnulaActionPerformed
        lblError.setText("----");
        DefaultTableModel model = (DefaultTableModel) tblListaPPVentaAnula.getModel();
       while(model.getRowCount()>0){
            model.removeRow(0);
        }
        VentaBusiness business=new VentaBusiness();
        
        VentaDto venta = new VentaDto();
        venta.setNumBoleta(txtNumBoleta.getText());
        try {
            venta=business.obtenerVenta(venta);
            lblCodigoVentaAnula.setText(venta.getCodVenta().toString());
            Date fecha=new Date(venta.getFechaVenta());
            lblFechaVentaAnula.setText(sdf.format(fecha));
            lblVentaTotalVentaAnula.setText(venta.getValorTotal().toString());
            List stocksBusqueda=venta.getStocks();
            Iterator iterador=stocksBusqueda.iterator();
            while(iterador.hasNext()){
                StockDto stock=(StockDto) iterador.next();
                Object[] fila=business.obtenerFilaTablaAnulaVenta(stock);
                model.addRow(fila);
            }
            
        } catch (Exception ex) {
            logger.debug("Error:"+ex.getMessage());
            lblError.setText(ex.getMessage());
        }
        
        
        
        
    }//GEN-LAST:event_bttBuscarVentaAnulaActionPerformed

    private void bttCancelarVentaAnulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttCancelarVentaAnulaActionPerformed
        this.dispose();
    }//GEN-LAST:event_bttCancelarVentaAnulaActionPerformed

    private void tblListaPPVentaAnulaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblListaPPVentaAnulaMouseClicked
        VentaBusiness business=new VentaBusiness();
        DefaultTableModel model = (DefaultTableModel) tblListaPPVentaAnula.getModel();
        int fila=tblListaPPVentaAnula.getSelectedRow();
        String codigo=(String) tblListaPPVentaAnula.getValueAt(fila, 0);
        Double valor=(Double) tblListaPPVentaAnula.getValueAt(fila, 2);
        boolean sw=false;
        try {
            Iterator iterador = stocks.iterator();
            while(iterador.hasNext()){
                 StockDto temp=(StockDto) iterador.next();
                 if(temp.getCodStock().equals(codigo)) sw=true;
            }
            if(!sw){
                Object[] options = {"Si","No"};
                int n = JOptionPane.showOptionDialog(this,
                    "¿Está seguro de que quiere anular esta venta?",
                    "",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    null);
                if(n==0){
                    btnAceptar.setEnabled(true);
                    StockDto stock=new StockDto();
                    stock.setCodStock(codigo);
                    sumaValor+=valor;
                    stocks.add(stock);
                
                
                }
            }
            
                
        } catch (Exception ex) {
            logger.debug("Error:"+ex.getMessage());
            lblError.setText(ex.getMessage());
        }
        
    }//GEN-LAST:event_tblListaPPVentaAnulaMouseClicked

    private void bttLimpiarVentaAnulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttLimpiarVentaAnulaActionPerformed
        limpiarformulario();
    }//GEN-LAST:event_bttLimpiarVentaAnulaActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        VentaBusiness business=new VentaBusiness();
        NotaCreditoDto notaCredito=new NotaCreditoDto();
        notaCredito.setDescripcion(txtDescripcion.getText());
        notaCredito.setFechaNotaCredito((new Date()).getTime());
        notaCredito.setValor(sumaValor);
        try {
            business.anularVenta(stocks,notaCredito);
            btnAceptar.setEnabled(false);
        } catch (Exception ex) {
            logger.debug("Error:"+ex.getMessage());
            lblError.setText(ex.getMessage());
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentaAnulaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentaAnulaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentaAnulaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentaAnulaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new VentaAnulaGui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton bttBuscarVentaAnula;
    private javax.swing.JButton bttCancelarVentaAnula;
    private javax.swing.JButton bttLimpiarVentaAnula;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblCodigoVentaAnula;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblFechaVentaAnula;
    private javax.swing.JLabel lblTituloAnulaVenta;
    private javax.swing.JLabel lblVentaTotalVentaAnula;
    private javax.swing.JTable tblListaPPVentaAnula;
    private javax.swing.JTextField txtDescripcion;
    private javax.swing.JTextField txtNumBoleta;
    // End of variables declaration//GEN-END:variables

    private void limpiarformulario() {
        txtNumBoleta.setText("");
        lblCodigoVentaAnula.setText("");
        lblFechaVentaAnula.setText("");
        lblVentaTotalVentaAnula.setText("");
        DefaultTableModel model = (DefaultTableModel) tblListaPPVentaAnula.getModel();
        while (model.getRowCount()>0){
            model.removeRow(0);
        }
    }
}
